<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.sn" placeholder="部门编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="filters.state" placeholder="请选择" clearable>
            <el-option label="禁用" value="0"></el-option>
            <el-option label="启用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="initPage">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="80">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="140" sortable>
      </el-table-column>
      <el-table-column prop="state" label="部门状态" width="140" >
        <template slot-scope="scope">
            <div slot="reference" >
              <el-tag size="medium" v-if="scope.row.state==1" type="success">启用</el-tag>
              <el-tag size="medium" v-if="scope.row.state==0" type="danger">禁用</el-tag>
            </div>
        </template>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="140" sortable>
      </el-table-column>
<!--      <el-table-column prop="dirPath" label="部门的上级分类层级id" width="120" sortable>
      </el-table-column>-->
      <el-table-column prop="manager.username" label="部门管理员" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
      </el-table-column>
<!--      <el-table-column prop="shop_id" label="店家id" min-width="180" sortable>
      </el-table-column>-->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          style="float:right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-col>

    <!--save界面-->
    <el-dialog :title=saveTitle :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员" prop="manager_id">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <!--label:指定选项标签为选项对象的某个属性值
              value:指定选项的值为选项对象的某个属性值-->
          <el-cascader :options="deptTree"
                       v-model="saveForm.parent_id"
                       clearable
                       :props="{
                          checkStrictly:true,
                          label:'name',
                          value:'id'
                       }"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
    
  </section>
</template>

<script>
export default {
  data() {
    return {
      //高级查询用
      filters: {
        name: '',
        sn:'',
        state:''
      },
      //部门信息
      depts: [],
      //总条数
      total: 0,
      //当前页
      currentPage: 1,
      //每页显示条数
      pageSize:10,
      //可以显示的条数
      pageSizes:[5, 10, 25, 50],
      //忙等
      listLoading: false,
      //员工信息
      emps:[],
      //需要批量删除的数据
      sels: [],
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      //save表单验证
      saveFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入部门编号', trigger: 'blur' }
        ],
        manager_id: [
          { required: true, message: '请输入管理员', trigger: 'blur' }
        ]
      },
      saveTitle:'',
      //save界面数据
      saveForm: {
        id:null,
        name: '',
        state: 0,
        sn:'',
        manager_id:'',
        parent_id:''
      },
      //部门级树
      deptTree:[]

    }
  },
  methods: {
    //页码改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUsers();
    },
    //每页显示条数改变
    handleSizeChange(val){
      this.pageSize=val
      this.getUsers()
    },
    //获取用户列表
    getUsers() {
      //将页码封装
      let para = {
        currentPage: this.currentPage,
        pageSize:this.pageSize,
        keyword: this.filters.name,
        sn:this.filters.sn,
        state:this.filters.state,
      };
      //开启忙等
      this.listLoading = true;
      //发送请求获取分页数据
      this.$http.post("/dept/pageList",para).then(res=>{
        //回显数据到表格
        this.depts=res.data.data
        //查询到的总条数
        this.total=res.data.total
        //关闭忙等
        this.listLoading = false

      })
    },
    initPage(){
      this.currentPage=1
      this.getUsers()
    },
    //获取员工信息
    getEmps(){
      this.$http.get("/emp").then(res=>{
        this.emps=res.data
      })
    },
    //获取部门级树
    getDeptTree(){
      this.$http.post("/dept/tree/"+this.saveForm.id).then(res=>{
        this.deptTree=res.data
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        //开启忙等
        this.listLoading = true;
        this.$http.delete("/dept/"+row.id).then(res=>{
          console.log(res)
          if (res.data.flag){
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.initPage()
          }else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
          this.listLoading =false
        })
        let para = { id: row.id };
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      if (this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();
      }
      this.saveTitle='编辑'
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      this.getDeptTree()
    },
    //绑定新增按钮
    handleAdd: function () {
      if (this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();
      }
      this.saveTitle='新增'
      this.saveFormVisible = true;
      this.saveForm = {
        name: '',
        state: 0,
        sn:'',
        manager_id:'',
        parent_id:''
      };
    },
    //提交修改数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //开启忙等
            this.saveLoading = true;
            if (this.saveForm.parent_id){//判断是否有上级部门
              //获取上级部门的id
              if(typeof this.saveForm.parent_id == "object"){
                this.saveForm.parent_id=this.saveForm.parent_id[this.saveForm.parent_id.length-1]
              }
            }
            //执行请求
            this.$http.put("/dept",this.saveForm).then(res=>{
              if (res.data.flag){//操作成功
                this.$message({
                  message:res.data.msg,
                  type:'success'
                })
              }else {
                this.$message({
                  message:res.data.msg,
                  type:'warning'
                })
              }
              //关闭忙等
              this.getDeptTree()
              this.saveLoading = false;
              //关闭模态框
              this.$refs['saveForm'].resetFields();
              this.saveFormVisible = false;
              this.getUsers()
            })
          });
        }
      });
    },

    //记录批量删除的数据信息
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      console.log(ids)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //开启忙等
        this.listLoading = true;
        this.$http.patch("/dept/dels",ids).then(res=>{
          console.log(res)
          if (res.data.flag){
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.getUsers()
          }else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
          this.listLoading=false
          this.getEmps()
        })

      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getUsers();
    this.getEmps();
    this.getDeptTree()
  }
}

</script>

<style scoped>

</style>